package code.ws_common_net.code
{
	import code.ws_common_interface.support.IDataPacket;
	import code.ws_common_interface.support.IResponsePool;
	import code.ws_common_net.utils.ByteBuffer;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.Socket;
	import flash.utils.ByteArray;

	public class ClientSocket
	{
		private var _dataBuffer:ByteArray;
		protected var socket:Socket;
		public static const HEAD_LENGTH:int = 4;
		private var len:int=-1;
		private var isReadHead : Boolean = false;
		private var responsePool:IResponsePool;
		
		public function ClientSocket()
		{
			_dataBuffer=new ByteArray();
		}
		public function connectServer(host:String,port:int):void
		{
			socket =new Socket();
			socket.connect(host,port);
			initListeners();
		}
		public function setResponsePool(responsePool:IResponsePool):void
		{
			this.responsePool=responsePool;
		}
		private function initListeners():void
		{
			socket.addEventListener(Event.CLOSE, closeHandler);
			socket.addEventListener(Event.CONNECT, connectHandler);
			socket.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			socket.addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
		}
		private function securityErrorHandler(event:SecurityErrorEvent):void
		{
			trace("错误");
		}
		private function closeHandler(event:Event):void
		{
			trace("断开");
		}
		private function connectHandler(event:Event):void
		{
			trace("成功");
		}
		private function ioErrorHandler(event:IOErrorEvent):void
		{
			trace("错误");
		}
		private function socketDataHandler(event:ProgressEvent):void
		{
			readData();
		}
		private function readData():void{
			if (!this.isReadHead && this.socket.bytesAvailable >= HEAD_LENGTH)//如果还没读过头部则读一次。
			{
				len = this.socket.readInt(); 
				this.isReadHead = true;
			}
			if (isReadHead && this.socket.bytesAvailable >= len)//如果读了头部，并且当前可读长度大于等于消息长度，则开始读取
			{
				_dataBuffer.clear();
				this.socket.readBytes(_dataBuffer, 0, len);
				
				//读分发码
				var _flag:int=_dataBuffer.readShort();
				var pos:int = _dataBuffer.position;
				var _bat:int=_dataBuffer.readByte();
				_dataBuffer.position=pos;
				
				if(_flag != 0)
				{
					var packet:IDataPacket = responsePool.getPacketClass(_flag);
					if(packet!=null){
						packet.setByteArrary(_dataBuffer);
						try
						{
							packet.hander();
						}
						catch(e:Error)
						{
							//trace(e.getStackTrace());
						}
					}
				}
				this.isReadHead = false;
			}
			else
			{
				return;
			}
			this.socket.bytesAvailable >= HEAD_LENGTH && this.readData();
		}
		
		
		
		
		/**
		 * 非阻塞发送数据
		 * @param data
		 *
		 */
		public function send(data:ByteBuffer):void
		{
			if (socket && socket.connected)
			{
				socket.writeInt(data.top());
				socket.writeBytes(data.toByteArray());
				socket.flush();
			}
			else
			{
				trace("断开连接，不写数据");
			}
		}
		/**关闭连接*/
		public function close():void
		{
			if(socket != null && socket.connected) {
				clear();
			}
		}
		private function clear():void
		{
			if (socket == null)
			{
				return;
			}
			
			if (socket.connected)
			{
				socket.close();
			}
			removeListener();
			socket=null;
		}
		private function removeListener():void{
			socket.removeEventListener(Event.CLOSE, closeHandler);
			socket.removeEventListener(Event.CONNECT, connectHandler);
			socket.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			socket.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			socket.removeEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
		}
	}
}